<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>聚类分析--基于共享单车数据集 | 杨一赫的博客</title><meta name="author" content="杨一赫"><meta name="copyright" content="杨一赫"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="聚类分析--基于共享单车数据集 杨一赫，连泽杰 数据预处理 导包 #调包import pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline#数据导入bike&#x3D;pd.read_csv(&amp;#x27;bike.csv&amp;#x27;) 数据基本情况 #查看数据类型bike.info()">
<meta property="og:type" content="article">
<meta property="og:title" content="聚类分析--基于共享单车数据集">
<meta property="og:url" content="http://yang1he.gitee.io/2022/12/05/%E8%81%9A%E7%B1%BB%E5%88%86%E6%9E%90--%E5%9F%BA%E4%BA%8E%E5%85%B1%E4%BA%AB%E5%8D%95%E8%BD%A6%E6%95%B0%E6%8D%AE%E9%9B%86/index.html">
<meta property="og:site_name" content="杨一赫的博客">
<meta property="og:description" content="聚类分析--基于共享单车数据集 杨一赫，连泽杰 数据预处理 导包 #调包import pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline#数据导入bike&#x3D;pd.read_csv(&amp;#x27;bike.csv&amp;#x27;) 数据基本情况 #查看数据类型bike.info()">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/output_40_0.png">
<meta property="article:published_time" content="2022-12-04T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-23T09:02:16.962Z">
<meta property="article:author" content="杨一赫">
<meta property="article:tag" content="-应用文章">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/output_40_0.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://yang1he.gitee.io/2022/12/05/%E8%81%9A%E7%B1%BB%E5%88%86%E6%9E%90--%E5%9F%BA%E4%BA%8E%E5%85%B1%E4%BA%AB%E5%8D%95%E8%BD%A6%E6%95%B0%E6%8D%AE%E9%9B%86/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6b9e2c1c603a1d11d43a9822bdd68c2c";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: {"limitDay":90,"position":"top","messagePrev":"距离上次更新已经","messageNext":"天本文可能会过期"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '聚类分析--基于共享单车数据集',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-02-23 17:02:16'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><script src="https://cdn.jsdelivr.net/npm/echarts@5.3.0/dist/echarts.min.js"></script><script src="https://cdn.jsdelivr.net/npm/echarts@4.7.0/map/js/china.min.js"></script><script src="node_modules/simplex-noise/simplex-noise.js"></script><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="杨一赫的博客" type="application/atom+xml">
</head><body><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pace-js/themes/blue/pace-theme-minimal.min.css"/><script src="https://cdn.jsdelivr.net/npm/pace-js/pace.min.js"></script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/favicon2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">14</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">7</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about"><i class="fa-fw fa fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/output_30_0.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">杨一赫的博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about"><i class="fa-fw fa fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">聚类分析--基于共享单车数据集</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-12-04T16:00:00.000Z" title="发表于 2022-12-05 00:00:00">2022-12-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-02-23T09:02:16.962Z" title="更新于 2023-02-23 17:02:16">2023-02-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">机器学习</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E5%8A%A8%E6%89%8B%E5%AD%A6%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">动手学机器学习</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="聚类分析--基于共享单车数据集"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="聚类分析--基于共享单车数据集">聚类分析--基于共享单车数据集</h1>
<p>杨一赫，连泽杰</p>
<h2 id="数据预处理">数据预处理</h2>
<h3 id="导包">导包</h3>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment">#调包</span></span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> seaborn <span class="keyword">as</span> sns</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line">%matplotlib inline</span><br><span class="line"><span class="comment">#数据导入</span></span><br><span class="line">bike=pd.read_csv(<span class="string">&#x27;bike.csv&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h3 id="数据基本情况">数据基本情况</h3>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment">#查看数据类型</span></span><br><span class="line">bike.info()</span><br></pre></td></tr></table></figure>
<pre><code>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;
RangeIndex: 6427 entries, 0 to 6426
Data columns (total 15 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   Unnamed: 0         6427 non-null   int64  
 1   user_id            6427 non-null   int64  
 2   start_time         6427 non-null   object 
 3   end_time           6427 non-null   object 
 4   timeduration       6427 non-null   int64  
 5   bikeid             6427 non-null   int64  
 6   tripduration       6427 non-null   object 
 7   from_station_id    6427 non-null   int64  
 8   from_station_name  6427 non-null   object 
 9   to_station_id      6427 non-null   int64  
 10  to_station_name    6427 non-null   object 
 11  usertype           6427 non-null   object 
 12  gender             5938 non-null   object 
 13  birthyear          5956 non-null   float64
 14  age                6427 non-null   object 
dtypes: float64(1), int64(6), object(8)
memory usage: 753.3+ KB</code></pre>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment">#查看缺失值</span></span><br><span class="line">bike.isnull().<span class="built_in">any</span>()</span><br><span class="line"><span class="comment">#查看缺失值占比</span></span><br><span class="line">bike.isnull().<span class="built_in">sum</span>()/<span class="built_in">len</span>(bike)</span><br><span class="line"><span class="comment">#用户数据具体情况</span></span><br><span class="line">bike.head()</span><br></pre></td></tr></table></figure>
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
    
    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>
</th>
<th>
Unnamed: 0
</th>
<th>
user_id
</th>
<th>
start_time
</th>
<th>
end_time
</th>
<th>
timeduration
</th>
<th>
bikeid
</th>
<th>
tripduration
</th>
<th>
from_station_id
</th>
<th>
from_station_name
</th>
<th>
to_station_id
</th>
<th>
to_station_name
</th>
<th>
usertype
</th>
<th>
gender
</th>
<th>
birthyear
</th>
<th>
age
</th>
</tr>
</thead>
<tbody>
<tr>
<th>
0
</th>
<td>
439283
</td>
<td>
21499218
</td>
<td>
11/14/2018 7:37
</td>
<td>
11/14/2018 7:44
</td>
<td>
7
</td>
<td>
2631
</td>
<td>
436
</td>
<td>
319
</td>
<td>
Greenview Ave &amp; Diversey Pkwy
</td>
<td>
67
</td>
<td>
Sheffield Ave &amp; Fullerton Ave
</td>
<td>
Subscriber
</td>
<td>
Male
</td>
<td>
1982.0
</td>
<td>
37
</td>
</tr>
<tr>
<th>
1
</th>
<td>
603317
</td>
<td>
21694389
</td>
<td>
12/18/2018 19:02
</td>
<td>
12/18/2018 19:10
</td>
<td>
7
</td>
<td>
1565
</td>
<td>
445
</td>
<td>
164
</td>
<td>
Franklin St &amp; Lake St
</td>
<td>
195
</td>
<td>
Columbus Dr &amp; Randolph St
</td>
<td>
Subscriber
</td>
<td>
Male
</td>
<td>
1988.0
</td>
<td>
31
</td>
</tr>
<tr>
<th>
2
</th>
<td>
109957
</td>
<td>
21110722
</td>
<td>
10/9/2018 12:37
</td>
<td>
10/9/2018 12:55
</td>
<td>
18
</td>
<td>
2231
</td>
<td>
1,090
</td>
<td>
163
</td>
<td>
Damen Ave &amp; Clybourn Ave
</td>
<td>
69
</td>
<td>
Damen Ave &amp; Pierce Ave
</td>
<td>
Customer
</td>
<td>
Male
</td>
<td>
1989.0
</td>
<td>
30
</td>
</tr>
<tr>
<th>
3
</th>
<td>
428082
</td>
<td>
21485409
</td>
<td>
11/12/2018 12:30
</td>
<td>
11/12/2018 12:40
</td>
<td>
9
</td>
<td>
4226
</td>
<td>
581
</td>
<td>
226
</td>
<td>
Racine Ave &amp; Belmont Ave
</td>
<td>
308
</td>
<td>
Seeley Ave &amp; Roscoe St
</td>
<td>
Subscriber
</td>
<td>
Female
</td>
<td>
1989.0
</td>
<td>
30
</td>
</tr>
<tr>
<th>
4
</th>
<td>
395437
</td>
<td>
21445994
</td>
<td>
11/7/2018 7:29
</td>
<td>
11/7/2018 7:35
</td>
<td>
6
</td>
<td>
3475
</td>
<td>
390
</td>
<td>
77
</td>
<td>
Clinton St &amp; Madison St
</td>
<td>
621
</td>
<td>
Aberdeen St &amp; Randolph St
</td>
<td>
Subscriber
</td>
<td>
Male
</td>
<td>
1979.0
</td>
<td>
40
</td>
</tr>
</tbody>
</table>
</div>
<h3 id="数据处理">数据处理</h3>
<ul>
<li>（1）删除对业务分析没有实际作用的变量：存在Unnamed:0这个对业务分析没有实际作用的字段，需要进行删除。</li>
<li>（2）删除空值：空值占比很小，可以直接删除，删除后可以看到没有空值了。</li>
</ul>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike.drop([<span class="string">&#x27;Unnamed: 0&#x27;</span>],axis=<span class="number">1</span>,inplace=<span class="literal">True</span>)</span><br><span class="line">bike.dropna(inplace=<span class="literal">True</span>)</span><br><span class="line">bike.isnull().<span class="built_in">any</span>()</span><br></pre></td></tr></table></figure>
<pre><code>user_id              False
start_time           False
end_time             False
timeduration         False
bikeid               False
tripduration         False
from_station_id      False
from_station_name    False
to_station_id        False
to_station_name      False
usertype             False
gender               False
birthyear            False
age                  False
dtype: bool</code></pre>
<h3 id="类别型变量处理">类别型变量处理</h3>
<ul>
<li>（1）将类别型变量转换成数字型变量：age和tripduration应该为数字型变量，而原始数据中为字符串变量，需要进行转换。</li>
<li>（2）gender和usertype是类别型变量，需要转变为哑变量。（usertype中0是订阅用户，1是非订阅用户。gender中0是男性，1是女性。）</li>
</ul>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike.age=pd.to_numeric(bike.age)</span><br><span class="line"><span class="comment">#转变tripduration的类型    tripduration中1,090，这种类型没法直接转变成数据型变量，我们可以先用replace函数把“，”去掉然后再转。</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike.tripduration=pd.to_numeric(bike.tripduration.apply(<span class="keyword">lambda</span> x:x.replace(<span class="string">&quot;,&quot;</span>,<span class="string">&quot;&quot;</span>)))</span><br><span class="line">bike.gender=pd.get_dummies(bike.gender).Female</span><br><span class="line">bike.usertype=pd.get_dummies(bike.usertype).Customer</span><br><span class="line">bike.info()</span><br></pre></td></tr></table></figure>
<pre><code>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;
Int64Index: 5938 entries, 0 to 6426
Data columns (total 14 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   user_id            5938 non-null   int64  
 1   start_time         5938 non-null   object 
 2   end_time           5938 non-null   object 
 3   timeduration       5938 non-null   int64  
 4   bikeid             5938 non-null   int64  
 5   tripduration       5938 non-null   int64  
 6   from_station_id    5938 non-null   int64  
 7   from_station_name  5938 non-null   object 
 8   to_station_id      5938 non-null   int64  
 9   to_station_name    5938 non-null   object 
 10  usertype           5938 non-null   uint8  
 11  gender             5938 non-null   uint8  
 12  birthyear          5938 non-null   float64
 13  age                5938 non-null   int64  
dtypes: float64(1), int64(7), object(4), uint8(2)
memory usage: 614.7+ KB</code></pre>
<h3 id="时间变量转变">时间变量转变</h3>
<p>将起始终止时间转换成datatime数据类型。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike.start_time=pd.to_datetime(bike.start_time)</span><br><span class="line">bike.end_time=pd.to_datetime(bike.end_time)</span><br></pre></td></tr></table></figure>
<p>发现年龄最大值有101，属于异常值，因此选择年龄合适的数据进行分析，即10-80岁。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike=bike[(bike.age&lt;=<span class="number">80</span>)]</span><br><span class="line">bike=bike[(bike.age&gt;=<span class="number">10</span>)]</span><br></pre></td></tr></table></figure>
<p>以上，数据的清洗结束。</p>
<h2 id="数据标准化">数据标准化</h2>
<p>数据预处理结束之后，需要找出合适的特征变量存入X中，并将数据进行标准化。我们选择timeduration、tripduration、usertype、gender、age来进行。可以先看下这些变量的相关关系：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">bike[[<span class="string">&#x27;timeduration&#x27;</span>,<span class="string">&#x27;tripduration&#x27;</span>,<span class="string">&#x27;usertype&#x27;</span>,<span class="string">&#x27;gender&#x27;</span>,<span class="string">&#x27;age&#x27;</span>]].corr()</span><br></pre></td></tr></table></figure>
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
    
    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>
</th>
<th>
timeduration
</th>
<th>
tripduration
</th>
<th>
usertype
</th>
<th>
gender
</th>
<th>
age
</th>
</tr>
</thead>
<tbody>
<tr>
<th>
timeduration
</th>
<td>
1.000000
</td>
<td>
0.269486
</td>
<td>
0.209317
</td>
<td>
0.053094
</td>
<td>
0.034074
</td>
</tr>
<tr>
<th>
tripduration
</th>
<td>
0.269486
</td>
<td>
1.000000
</td>
<td>
0.065112
</td>
<td>
0.006165
</td>
<td>
-0.007491
</td>
</tr>
<tr>
<th>
usertype
</th>
<td>
0.209317
</td>
<td>
0.065112
</td>
<td>
1.000000
</td>
<td>
0.023600
</td>
<td>
-0.046397
</td>
</tr>
<tr>
<th>
gender
</th>
<td>
0.053094
</td>
<td>
0.006165
</td>
<td>
0.023600
</td>
<td>
1.000000
</td>
<td>
-0.072825
</td>
</tr>
<tr>
<th>
age
</th>
<td>
0.034074
</td>
<td>
-0.007491
</td>
<td>
-0.046397
</td>
<td>
-0.072825
</td>
<td>
1.000000
</td>
</tr>
</tbody>
</table>
</div>
<p>查看相关性，发现timeduration和tripduration相关性略强，选其一进行分析。将数据存入X，并进行数据标准化。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">x=bike[[<span class="string">&#x27;timeduration&#x27;</span>,<span class="string">&#x27;usertype&#x27;</span>,<span class="string">&#x27;gender&#x27;</span>,<span class="string">&#x27;age&#x27;</span>]]</span><br><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> scale</span><br><span class="line">x=pd.DataFrame(scale(x))</span><br></pre></td></tr></table></figure>
<h2 id="建立模型">建立模型</h2>
<h3 id="尝试不同分类的模型拟合">尝试不同分类的模型拟合</h3>
<p>拟合模型，首先可以尝试将群体分为三类：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> cluster</span><br><span class="line">model=cluster.KMeans(n_clusters=<span class="number">3</span>, random_state=<span class="number">10</span>)</span><br><span class="line">model.fit(x)</span><br></pre></td></tr></table></figure>
<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: "▸";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: "▾";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: "";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: "";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: "";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style>
<div id="sk-container-id-1" class="sk-top-container">
<div class="sk-text-repr-fallback">
<pre>KMeans(n_clusters=3, random_state=10)</pre>
<b>In a Jupyter environment, please rerun this cell to show the HTML
representation or trust the notebook. <br />On GitHub, the HTML
representation is unable to render, please try loading this page with
nbviewer.org.</b>
</div>
<div class="sk-container" hidden="">
<div class="sk-item">
<div class="sk-estimator sk-toggleable">
<input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-1" type="checkbox" checked><label for="sk-estimator-id-1" class="sk-toggleable__label sk-toggleable__label-arrow">KMeans</label>
<div class="sk-toggleable__content">
<pre>KMeans(n_clusters=3, random_state=10)</pre>
</div>
</div>
</div>
</div>
</div>
<h3 id="可视化和groupby评估分群效果">可视化和groupby()评估分群效果</h3>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike[<span class="string">&#x27;cluster&#x27;</span>]=model.labels_</span><br><span class="line">sns.scatterplot(x=<span class="string">&#x27;gender&#x27;</span>, y=<span class="string">&#x27;usertype&#x27;</span>, hue=<span class="string">&#x27;cluster&#x27;</span>, data=bike)</span><br></pre></td></tr></table></figure>
<pre><code>&lt;AxesSubplot: xlabel=&#39;gender&#39;, ylabel=&#39;usertype&#39;&gt;</code></pre>
<p>​<br />
<img
src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/output_30_1.png"
alt="png" /> ​</p>
<p>对‘gender’和'usertype'进行可视化（X,Y都挑0,1变量，比较好观察），理论上有4种结合可能，可视化的结果也很明显得展现了3种类别，分在4个角，说明这两个是比较好的特征变量。</p>
<p>第0组类型是customer，性别都有；</p>
<p>第1组类型是subscriber，性别为男；</p>
<p>第2组类型是subscriber，性别为女。</p>
<p>使用groupby函数分析单变量维度的分群结果，这将有助于我们粗略理解每个人群在每个选定的特征变量上的分群效果。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike.groupby([<span class="string">&#x27;cluster&#x27;</span>]).gender.describe()</span><br></pre></td></tr></table></figure>
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
    
    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>
</th>
<th>
count
</th>
<th>
mean
</th>
<th>
std
</th>
<th>
min
</th>
<th>
25%
</th>
<th>
50%
</th>
<th>
75%
</th>
<th>
max
</th>
</tr>
<tr>
<th>
cluster
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>
0
</th>
<td>
1245.0
</td>
<td>
1.000000
</td>
<td>
0.000000
</td>
<td>
1.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
</tr>
<tr>
<th>
1
</th>
<td>
4484.0
</td>
<td>
0.000000
</td>
<td>
0.000000
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
</tr>
<tr>
<th>
2
</th>
<td>
207.0
</td>
<td>
0.270531
</td>
<td>
0.445311
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
</tr>
</tbody>
</table>
</div>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike.groupby([<span class="string">&#x27;cluster&#x27;</span>]).usertype.describe()</span><br></pre></td></tr></table></figure>
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
    
    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>
</th>
<th>
count
</th>
<th>
mean
</th>
<th>
std
</th>
<th>
min
</th>
<th>
25%
</th>
<th>
50%
</th>
<th>
75%
</th>
<th>
max
</th>
</tr>
<tr>
<th>
cluster
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>
0
</th>
<td>
1245.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
</tr>
<tr>
<th>
1
</th>
<td>
4484.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
<td>
0.0
</td>
</tr>
<tr>
<th>
2
</th>
<td>
207.0
</td>
<td>
1.0
</td>
<td>
0.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
<td>
1.0
</td>
</tr>
</tbody>
</table>
</div>
<p>groupby同样可以得出一样的结果。</p>
<h3 id="使用轮廓系数评估模型效果">使用轮廓系数评估模型效果</h3>
<p>当聚类个数为3个时，评估模型的效果，轮廓系数为0.47(评分越高，个体与群的距离越近，模型效果越好)。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> metrics<span class="comment">#调用sklearn的metrics库</span></span><br><span class="line">x_cluster=model.fit_predict(x)<span class="comment">#个体与群的距离</span></span><br><span class="line">score=metrics.silhouette_score(x,x_cluster)<span class="comment">#评分越高，个体与群越近；评分越低，个体与群越远</span></span><br><span class="line"><span class="built_in">print</span>(score)</span><br></pre></td></tr></table></figure>
<pre><code>0.47528572281121667</code></pre>
<h3 id="优化模型">优化模型</h3>
<p>利用“肘”方法找出最佳聚类个数：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.cluster <span class="keyword">import</span> KMeans</span><br><span class="line">wcss = []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="number">11</span>):</span><br><span class="line">    kmeans = KMeans(n_clusters = i, init = <span class="string">&#x27;k-means++&#x27;</span>, random_state =<span class="number">42</span>)</span><br><span class="line">    kmeans.fit(x)</span><br><span class="line">    wcss.append(kmeans.inertia_)</span><br><span class="line">plt.plot(<span class="built_in">range</span>(<span class="number">1</span>, <span class="number">11</span>), wcss)</span><br><span class="line">plt.title(<span class="string">&#x27;The Elbow Method&#x27;</span>)</span><br><span class="line">plt.xlabel(<span class="string">&#x27;Number of clusters&#x27;</span>)</span><br><span class="line">plt.ylabel(<span class="string">&#x27;WCSS&#x27;</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<figure>
<img
src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/output_40_0.png"
alt="png" />
<figcaption aria-hidden="true">png</figcaption>
</figure>
<p>快速下降趋于平缓下降的转折点是聚类最好的情况，即图中为5时。
调整模型，最后的结果是0.49。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">model=cluster.KMeans(n_clusters=<span class="number">5</span>, random_state=<span class="number">10</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">x_cluster=model.fit_predict(x)<span class="comment">#个体与群的距离</span></span><br><span class="line">score=metrics.silhouette_score(x,x_cluster)<span class="comment">#评分越高，个体与群越近；评分越低，个体与群越远</span></span><br><span class="line"><span class="built_in">print</span>(score)</span><br></pre></td></tr></table></figure>
<pre><code>0.49042475787709033</code></pre>
<h2 id="业务解读">业务解读</h2>
<p>将结果导出成为CSV之后，重点关注每一列数据的绝对值，绝对值越大，则说明这个群体在相应的特征上有着更明显区分度。可以结合聚类结果，根据自己对业务的理解思考不同人群的特征。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">centers=pd.DataFrame(model.cluster_centers_)</span><br><span class="line">centers.to_csv(<span class="string">&#x27;bike_center_5.csv&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>查看分群的各自占比，类0最多，类0，2，4都是有相当数量的群体，类1，3只占很小一部分。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">bike[<span class="string">&#x27;cluster&#x27;</span>]=model.labels_</span><br><span class="line">bike[<span class="string">&#x27;cluster&#x27;</span>].value_counts(<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<pre><code>0    0.483996
2    0.198113
4    0.187500
1    0.095519
3    0.034872
Name: cluster, dtype: float64</code></pre>
<p>与导出的表格的数据是一致的，只是更便于查看。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">centers.columns=[<span class="string">&#x27;timeduration&#x27;</span>,<span class="string">&#x27;usertype&#x27;</span>,<span class="string">&#x27;gender&#x27;</span>,<span class="string">&#x27;age&#x27;</span>]</span><br><span class="line"><span class="built_in">print</span>(centers)</span><br></pre></td></tr></table></figure>
<pre><code>   timeduration  usertype    gender       age
0     -0.367463 -0.190084 -0.529802 -0.484353
1      2.042150 -0.190084 -0.307325 -0.076050
2     -0.082660 -0.190084  1.887497 -0.183774
3      1.101180  5.260830  0.124153 -0.244085
4     -0.204937 -0.190084 -0.492880  1.529314</code></pre>
<p>第一列是群组，重点关注每一列的数据，找出绝对值最大的数，如果人群在某个特征变量上数据的绝对值比较大，就说明这个人群在这个特征上有较明显的区分度。</p>
<p>可以看到，0群是男性，较年轻，骑行时间较短的用户，占比48.4%；1群是骑行时间较长的用户，占比9.6%；2群是女性群体，占比19.8%；3群是非订阅用户，占比3.5%；4群是年龄较大的用户，占比18.8%</p>
<p>业务建议：优先满足核心用户群，0群。通过该群体人数规模大的优势进行品牌宣传扩大品牌影响力。</p>
<h2 id="感谢您的观看">感谢您的观看</h2>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://yang1he.gitee.io">杨一赫</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://yang1he.gitee.io/2022/12/05/%E8%81%9A%E7%B1%BB%E5%88%86%E6%9E%90--%E5%9F%BA%E4%BA%8E%E5%85%B1%E4%BA%AB%E5%8D%95%E8%BD%A6%E6%95%B0%E6%8D%AE%E9%9B%86/">http://yang1he.gitee.io/2022/12/05/%E8%81%9A%E7%B1%BB%E5%88%86%E6%9E%90--%E5%9F%BA%E4%BA%8E%E5%85%B1%E4%BA%AB%E5%8D%95%E8%BD%A6%E6%95%B0%E6%8D%AE%E9%9B%86/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://yang1he.gitee.io" target="_blank">杨一赫的博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E5%BA%94%E7%94%A8%E6%96%87%E7%AB%A0/">-应用文章</a></div><div class="post_share"><div class="social-share" data-image="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/output_40_0.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/01/06/Chatpt%E9%AB%98%E6%95%88%E4%BD%BF%E7%94%A8%E6%8A%80%E5%B7%A7%E2%80%94%E2%80%94%E5%9F%BA%E4%BA%8ETransformer%E6%A8%A1%E5%9E%8B%E5%8E%9F%E7%90%86/"><img class="prev-cover" src="https://img-blog.csdnimg.cn/img_convert/168ab6b97255b7565b515514b6563393.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Chatgpt高效使用技巧——基于Transformer模型原理</div></div></a></div><div class="next-post pull-right"><a href="/2022/11/23/GNN%E7%BB%BC%E8%BF%B0%E7%A0%94%E8%AF%BB/"><img class="next-cover" src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/v2-a489a8f84b998439d6e681dc07a13080_720w.webp" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">GNN综述研读</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/01/06/Chatpt%E9%AB%98%E6%95%88%E4%BD%BF%E7%94%A8%E6%8A%80%E5%B7%A7%E2%80%94%E2%80%94%E5%9F%BA%E4%BA%8ETransformer%E6%A8%A1%E5%9E%8B%E5%8E%9F%E7%90%86/" title="Chatgpt高效使用技巧——基于Transformer模型原理"><img class="cover" src="https://img-blog.csdnimg.cn/img_convert/168ab6b97255b7565b515514b6563393.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-06</div><div class="title">Chatgpt高效使用技巧——基于Transformer模型原理</div></div></a></div><div><a href="/2023/02/28/GPTEX---%E4%B8%BAChatGPT%E8%80%8C%E7%94%9F%E7%9A%84latex%E8%BD%AF%E4%BB%B6/" title="GPTEX---为ChatGPT而生的latex软件"><img class="cover" src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/image-20230228145723183.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-28</div><div class="title">GPTEX---为ChatGPT而生的latex软件</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/favicon2.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">杨一赫</div><div class="author-info__description">阳光开朗大男孩</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">14</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">7</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/yang1he"><i class="fab fa-github"></i><span>gitee</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">平平无奇的网站</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%81%9A%E7%B1%BB%E5%88%86%E6%9E%90--%E5%9F%BA%E4%BA%8E%E5%85%B1%E4%BA%AB%E5%8D%95%E8%BD%A6%E6%95%B0%E6%8D%AE%E9%9B%86"><span class="toc-number">1.</span> <span class="toc-text">聚类分析--基于共享单车数据集</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E9%A2%84%E5%A4%84%E7%90%86"><span class="toc-number">1.1.</span> <span class="toc-text">数据预处理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%BC%E5%8C%85"><span class="toc-number">1.1.1.</span> <span class="toc-text">导包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%9F%BA%E6%9C%AC%E6%83%85%E5%86%B5"><span class="toc-number">1.1.2.</span> <span class="toc-text">数据基本情况</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86"><span class="toc-number">1.1.3.</span> <span class="toc-text">数据处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E5%88%AB%E5%9E%8B%E5%8F%98%E9%87%8F%E5%A4%84%E7%90%86"><span class="toc-number">1.1.4.</span> <span class="toc-text">类别型变量处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%97%B6%E9%97%B4%E5%8F%98%E9%87%8F%E8%BD%AC%E5%8F%98"><span class="toc-number">1.1.5.</span> <span class="toc-text">时间变量转变</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E6%A0%87%E5%87%86%E5%8C%96"><span class="toc-number">1.2.</span> <span class="toc-text">数据标准化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BB%BA%E7%AB%8B%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.3.</span> <span class="toc-text">建立模型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%9D%E8%AF%95%E4%B8%8D%E5%90%8C%E5%88%86%E7%B1%BB%E7%9A%84%E6%A8%A1%E5%9E%8B%E6%8B%9F%E5%90%88"><span class="toc-number">1.3.1.</span> <span class="toc-text">尝试不同分类的模型拟合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%AF%E8%A7%86%E5%8C%96%E5%92%8Cgroupby%E8%AF%84%E4%BC%B0%E5%88%86%E7%BE%A4%E6%95%88%E6%9E%9C"><span class="toc-number">1.3.2.</span> <span class="toc-text">可视化和groupby()评估分群效果</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E8%BD%AE%E5%BB%93%E7%B3%BB%E6%95%B0%E8%AF%84%E4%BC%B0%E6%A8%A1%E5%9E%8B%E6%95%88%E6%9E%9C"><span class="toc-number">1.3.3.</span> <span class="toc-text">使用轮廓系数评估模型效果</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%98%E5%8C%96%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.3.4.</span> <span class="toc-text">优化模型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%9A%E5%8A%A1%E8%A7%A3%E8%AF%BB"><span class="toc-number">1.4.</span> <span class="toc-text">业务解读</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%84%9F%E8%B0%A2%E6%82%A8%E7%9A%84%E8%A7%82%E7%9C%8B"><span class="toc-number">1.5.</span> <span class="toc-text">感谢您的观看</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/06/24/An%20Intelligent%20Mobile%20Prediction%20method/" title="An Intelligent Mobile Prediction method with Mini-batch HTIA-based Seq2Seq Networks"><img src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/model_00.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="An Intelligent Mobile Prediction method with Mini-batch HTIA-based Seq2Seq Networks"/></a><div class="content"><a class="title" href="/2023/06/24/An%20Intelligent%20Mobile%20Prediction%20method/" title="An Intelligent Mobile Prediction method with Mini-batch HTIA-based Seq2Seq Networks">An Intelligent Mobile Prediction method with Mini-batch HTIA-based Seq2Seq Networks</a><time datetime="2023-06-23T16:00:00.000Z" title="发表于 2023-06-24 00:00:00">2023-06-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/03/05/%E5%A6%82%E4%BD%95%E8%8E%B7%E5%8F%96%E4%BD%A0%E4%B8%AA%E4%BA%BA%E8%B4%A6%E5%8F%B7%E7%9A%84openai%E7%9A%84api/" title="无题"><img src="/img/rick1.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="无题"/></a><div class="content"><a class="title" href="/2023/03/05/%E5%A6%82%E4%BD%95%E8%8E%B7%E5%8F%96%E4%BD%A0%E4%B8%AA%E4%BA%BA%E8%B4%A6%E5%8F%B7%E7%9A%84openai%E7%9A%84api/" title="无题">无题</a><time datetime="2023-03-05T05:57:17.050Z" title="发表于 2023-03-05 13:57:17">2023-03-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/03/04/%E4%B8%89%E5%88%86%E9%92%9F4%E8%A1%8C%E5%91%BD%E4%BB%A4%E6%9E%84%E5%BB%BAchatgpt%20webapp,%E6%94%AF%E6%8C%81%E9%AB%98%E5%B9%B6%E5%8F%91%E4%BB%A5%E5%8F%8A%E4%B8%8A%E4%B8%8B%E6%96%87%E5%AF%B9%E8%AF%9D%E5%8A%9F%E8%83%BD/" title="三分钟4行命令构建chatgpt webapp,支持高并发以及上下文对话功能"><img src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/image-20230305093941469.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="三分钟4行命令构建chatgpt webapp,支持高并发以及上下文对话功能"/></a><div class="content"><a class="title" href="/2023/03/04/%E4%B8%89%E5%88%86%E9%92%9F4%E8%A1%8C%E5%91%BD%E4%BB%A4%E6%9E%84%E5%BB%BAchatgpt%20webapp,%E6%94%AF%E6%8C%81%E9%AB%98%E5%B9%B6%E5%8F%91%E4%BB%A5%E5%8F%8A%E4%B8%8A%E4%B8%8B%E6%96%87%E5%AF%B9%E8%AF%9D%E5%8A%9F%E8%83%BD/" title="三分钟4行命令构建chatgpt webapp,支持高并发以及上下文对话功能">三分钟4行命令构建chatgpt webapp,支持高并发以及上下文对话功能</a><time datetime="2023-03-03T16:00:00.000Z" title="发表于 2023-03-04 00:00:00">2023-03-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/03/03/%E5%A4%9A%E6%A0%87%E7%AD%BE%E5%88%86%E7%B1%BB%E7%9A%84CrossEntropyLoss%E5%88%B0%E5%BA%95%E9%9C%80%E4%B8%8D%E9%9C%80%E8%A6%81One-Hot%E7%BC%96%E7%A0%81/" title="多标签分类的CrossEntropyLoss到底需不需要One-Hot编码"><img src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/image-20230303211538791.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="多标签分类的CrossEntropyLoss到底需不需要One-Hot编码"/></a><div class="content"><a class="title" href="/2023/03/03/%E5%A4%9A%E6%A0%87%E7%AD%BE%E5%88%86%E7%B1%BB%E7%9A%84CrossEntropyLoss%E5%88%B0%E5%BA%95%E9%9C%80%E4%B8%8D%E9%9C%80%E8%A6%81One-Hot%E7%BC%96%E7%A0%81/" title="多标签分类的CrossEntropyLoss到底需不需要One-Hot编码">多标签分类的CrossEntropyLoss到底需不需要One-Hot编码</a><time datetime="2023-03-02T16:00:00.000Z" title="发表于 2023-03-03 00:00:00">2023-03-03</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/28/GPTEX---%E4%B8%BAChatGPT%E8%80%8C%E7%94%9F%E7%9A%84latex%E8%BD%AF%E4%BB%B6/" title="GPTEX---为ChatGPT而生的latex软件"><img src="https://nmhjklnm.oss-cn-beijing.aliyuncs.com/article-img/img/image-20230228145723183.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="GPTEX---为ChatGPT而生的latex软件"/></a><div class="content"><a class="title" href="/2023/02/28/GPTEX---%E4%B8%BAChatGPT%E8%80%8C%E7%94%9F%E7%9A%84latex%E8%BD%AF%E4%BB%B6/" title="GPTEX---为ChatGPT而生的latex软件">GPTEX---为ChatGPT而生的latex软件</a><time datetime="2023-02-27T16:00:00.000Z" title="发表于 2023-02-28 00:00:00">2023-02-28</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By 杨一赫</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.1
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container').forEach(node => {
            if (node.hasAttribute('display')) {
              btf.wrap(node, 'div', { class: 'mathjax-overflow' })
            } else {
              btf.wrap(node, 'span', { class: 'mathjax-overflow' })
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>(() => {
  const $mermaidWrap = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaidWrap.length) {
    window.runMermaid = () => {
      window.loadMermaid = true
      const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

      Array.from($mermaidWrap).forEach((item, index) => {
        const mermaidSrc = item.firstElementChild
        const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
        const mermaidID = 'mermaid-' + index
        const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent
        mermaid.mermaidAPI.render(mermaidID, mermaidDefinition, (svgCode) => {
          mermaidSrc.insertAdjacentHTML('afterend', svgCode)
        })
      })
    }

    const loadMermaid = () => {
      window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
    }

    window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
  }
})()</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: '5a73aec03d8a0aeb971f',
      clientSecret: '54ad1c8adab95b382d582c73e9f597781de43525',
      repo: 'comment',
      owner: 'nmhjklnm',
      admin: ['nmhjklnm'],
      id: 'c3dfd1622c47d5d267a50e135ee59a6f',
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="//code.tidio.co/6zvu6bgfljrvvv9rw1y7hzehoriklr03.js" async="async"></script><script>function onTidioChatApiReady() {
  window.tidioChatApi.hide();
  window.tidioChatApi.on("close", function() {
    window.tidioChatApi.hide();
  });
}
if (window.tidioChatApi) {
  window.tidioChatApi.on("ready", onTidioChatApiReady);
} else {
  document.addEventListener("tidioChat-ready", onTidioChatApiReady);
}

var chatBtnFn = () => {
  document.getElementById("chat_btn").addEventListener("click", function(){
    window.tidioChatApi.show();
    window.tidioChatApi.open();
  });
}
chatBtnFn()
</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>